package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    /**
     * 保存账户信息
     *
     * @param map {"amount":100,"orderNo":"zs1788470360074436608","title":"新用户注册，赠送礼金","userId":16}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAccount(Map map) {
        //1.保存账户信息
        Integer userIdInt = (Integer) map.get("userId");
        Long userId = Long.valueOf(userIdInt);
        Integer amountInt = (Integer) map.get("amount");
        BigDecimal amount = BigDecimal.valueOf(amountInt);
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(amount);
        userAccount.setLockAmount(new BigDecimal("0.00"));
        userAccount.setAvailableAmount(amount);
        userAccount.setTotalIncomeAmount(amount);
        userAccount.setTotalPayAmount(new BigDecimal("0.00"));
        userAccountMapper.insert(userAccount);
        //2.新增账户变动日志
        String title = (String) map.get("title");
        String orderNo = (String) map.get("orderNo");
        this.saveUserAccountDetail(userId, title, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, amount, orderNo);
    }

    /**
     * 保存账户变动日志
     *
     * @param userId    用户ID
     * @param title     变动内容
     * @param tradeType 交易类型
     * @param amount    金额
     * @param orderNo   订单编号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 获取当前用户账户可用余额
     *
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);
        if (userAccount != null) {
            return userAccount.getAvailableAmount();
        }
        return null;
    }

    /**
     * 检查指定用户余额且完成余额扣减
     * 1.检查余额扣减余额
     * 2.新增账户变动日志
     *
     * @param accountDeductVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkAndDeduct(AccountDeductVo accountDeductVo) {
        //1.检查余额扣减余额
        int count = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (count == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
            //任意分支事务中，采用手动回滚全局事务
            //GlobalTransaction tx = GlobalTransactionContext.reload(RootContext.getXID());
            //tx.rollback();
            //GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
            //try {
            //    tx.rollback();
            //} catch (TransactionException e) {
            //    throw new RuntimeException(e);
            //}
        }
        //2.新增账户变动日志
        this.saveUserAccountDetail(accountDeductVo.getUserId(), accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
    }

    /**
     * 余额充值
     * @param userId
     * @param rechargeAmount
     */
    @Override
    public void recharge(Long userId, BigDecimal rechargeAmount) {
        userAccountMapper.recharge(userId, rechargeAmount);
    }

    @Override
    public void getUserAccountDetailPage(Page<UserAccountDetail> pageInfo, Long userId, String tradeType) {
        userAccountDetailMapper.getUserAccountDetail(pageInfo, userId, tradeType);
    }
}
